package Service;

import java.sql.*;

/**
 * @author 文永达
 * @title: DBService
 * @projectName jiaowuglxt
 * @description: TODO
 * @date 2021/1/20 11:17
 */
public class DBService {
    private String driver = "com.mysql.cj.jdbc.Driver";
    private String url = "jdbc:mysql://localhost:3306/jiaowuglxt?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
    String user = "root";
    String password = "Wyd210213";

    private Connection conn;
    private Statement stmt;
    private ResultSet rs;

    private void getConnection(){
        try {
            Class.forName(driver);
            this.conn = DriverManager.getConnection(url,user,password);
        } catch (ClassNotFoundException | SQLException e){
            e.printStackTrace();
        }
    }

    public ResultSet querySQL(String sql){
        try {
            if(this.conn == null)
                this.getConnection();
            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
            rs = stmt.executeQuery(sql);
        } catch (SQLException e){
            e.printStackTrace();
        }
        return rs;
    }

    public int updateSQL(String sql){
        int i = 0;
        try {
            if(this.conn == null)
                this.getConnection();
            stmt = conn.createStatement();
            i = stmt.executeUpdate(sql);
        } catch (SQLException e){
            e.printStackTrace();
        }
        return i;
    }

    private void close() {
        try {
            if (null != this.rs)
                rs.close();
            if (null != this.stmt)
                this.stmt.close();
            if (null != this.conn)
                this.conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
